package com.t309.tzy.controller;
import com.alibaba.fastjson.JSON;
import com.t309.tzy.constant.SessionConstant;
import com.t309.tzy.entity.TSysUser;
import com.t309.tzy.service.ITsysUserService;
import com.t309.tzy.utils.PageSupport;
import org.apache.log4j.Logger;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Controller//用注解配置 控制器
@RequestMapping("/user")//配置控制器路径
public class TSysUserController {
    private Logger log = Logger.getLogger("TSysUserController");
    /**
     * 父容器(Spring) 可以调用 子容器 (Spring MVC), IoC(控制反转)创建IUserService对象
     */
    @Resource
    private ITsysUserService userService;
    /**
     * 转到登录视图
     * @return 转到登录视图
     */
    @RequestMapping( "/toLogin")
    public String toLogin(){
        //System.out.println("[ 724 - TSysUserController => /login ]");
        log.info("User724Controller : sysuser/login ==================");
        //跳转到指定视图 //跳转到 client/login.jsp
        //return "WEB-INF/jsp/login";
        //return "WEB-INF/jsp/sysUser/login";
        return "login";
    }

    /**
     * 登录控制
     * @param model     出参
     * @param account   入参
     * @param password  入参
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IOException
     */
    @GetMapping("/login")
    //@PostMapping("/login")
    public String doLogin(Model model, @RequestParam String account, @RequestParam String password,
                          HttpServletRequest request, HttpServletResponse response,
                          HttpSession session) throws IOException {

        log.info("login====================================");
        //调用service方法，进行用户登录
        final int login = userService.login(account, password);
        session = request.getSession();
        if( login>0 ){    //登录成功
            log.info("doLogin() : 登录成功");
            int id = userService.getUserIdByAccount(account);
            System.err.println("doLogin()id="+id);
            TSysUser user = new TSysUser();
            user.setId(id);
            user.setAccount(account);
            //放入session
            session.setAttribute(SessionConstant.USER_SESSION, user);
//            log.info("SessionConstant.USERNAME_IN_SESSION(username)="+
//                        session.getAttribute(SessionConstant.USERNAME_IN_SESSION ));
            //页面跳转（xxx.jsp）
            return "redirect:/user/toMain";
            //return "frame";
        }else{
            //登录失败
            //request.getSession().setAttribute("error", "用户名或密码不正确");
            request.setAttribute("error", "用户名或密码不正确");
            return "login";//跳转到视图名
        }
    }




    /**
     * 退出登录
     * @param session Http会话
     * @return 重定向到登录视图
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute( SessionConstant.USERNAME_IN_SESSION);
        return "redirect:/user/toLogin";
    }

    /**
     * 转到欢迎页视图
     * @param session HttpSession会话
     * @return 跳转到欢迎页视图名
     */
    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        log.info("/toMain====================================");
        log.info("SessionConstant.USER_SESSION(user)="+
                session.getAttribute(SessionConstant.USER_SESSION ));
        if (session.getAttribute(SessionConstant.USER_SESSION) == null) {
            return "redirect:/user/login";
        }
        return "/frame";//转到欢迎页
    }

    /**
     * 转到用户信息视图
     * @param session
     * @return 返回:用户信息视图
     */
    @RequestMapping("/list")
    public String toUserList(HttpSession session, Model model) {
        log.info( "session : user="+ session.getAttribute( SessionConstant.USER_SESSION) );
        if (session.getAttribute( SessionConstant.USER_SESSION) == null) {
            return "redirect:/user/login";
        } else if (session.getAttribute("roleList") == null) {
            //List<TSysRole> roleList = roleService.getRoleList();
            //分页获取所有用户和角色
            List<TSysUser> userList = userService.getAllUsersByPage(0,8);
            session.setAttribute("userList", userList);
            //重定向到
            return "redirect:/user/getUserList";
        } else if (model.getAttribute("userList") == null) {
            return "redirect:/user/getUserList";
        }
        return "/sysUser/list";
    }

    /**
     * 获取用户列表
     * @param model
     * @param realName
     * @param roleId
     * @param pageIndex
     * @return 用户列表list
     */
    @RequestMapping("/getUserList")
    public String getUserList(Model model, String realName, Integer roleId, Integer pageIndex) {
        System.err.println("getUserList(): realName="+realName+",roleId="+roleId+",pageIndex="+pageIndex);
        PageSupport pageSupport = new PageSupport();
        //设置每页显示的数量
        pageSupport.setPageSize(7);
        if (pageIndex != null) {
            pageSupport.setCurrentPageNo(pageIndex);
        } else {
            pageSupport.setCurrentPageNo(1);
        }
        //设置总记录数, 调用获取所有记录数的方法
        pageSupport.setTotalCount(userService.getUserCount(realName, roleId));
        //
        pageSupport.setPagelimit((pageSupport.getCurrentPageNo() - 1) * 10);
        //根据真实姓名和角色编号查询用户列表
        List<TSysUser> list = userService.getUserListPagingByRealNameAndRoleId(realName, roleId, pageSupport);

        model.addAttribute("pageSupport", pageSupport);
        //model.addAttribute("userList", list);
        return "/sysUser/list";
    }

    /**
     * 转到添加用户视图
     * @param session
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAddUser(HttpSession session){
        log.info("session.getAttribute(SessionConstant.USERNAME_IN_SESSION)="+session.getAttribute(SessionConstant.USERNAME_IN_SESSION));
        if(session.getAttribute(SessionConstant.USERNAME_IN_SESSION) != null){
            return "/sysUser/add";
        }
        return "redirect:/user/toLogin";
    }

    /**
     * 添加用户
     * @param request
     * @param session
     * @param account
     * @param realName
     * @param password
     * @param sex
     * @param birthday
     * @param phone
     * @param address
     * @param roleId
     * @param attachs
     * @return
     * @throws IOException
     */
    @PostMapping("/add")
    public String addUser(HttpServletRequest request, HttpSession session, String account,
                          String realName, String password, Integer sex,
                          @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
                          String phone, String address, Integer roleId,
                          @RequestParam(value = "attachs",required = false) MultipartFile[] attachs)
            throws IOException {
        log.info("addUser()====================================");
         String errorInfo = null;
        boolean flag = true;

        TSysUser user = new TSysUser();
        //添加用户的管理员的信息
        //TSysUser createdUser = (TSysUser) session.getAttribute( SessionConstant.USERNAME_IN_SESSION );
        user.setAccount(account);
        user.setRealName(realName);
        user.setPassword(password);
        user.setSex(sex);
        user.setBirthday(birthday);
        user.setPhone(phone);
        user.setAddress(address);
        user.setRoleId(roleId);
        //user.setCreatedUserId(createdUser.getId());


        final int insert = userService.insert(user);
        if(insert>0){
            System.out.println("==添加成功==");
        }else{
            System.out.println("添加失败");
        }

        return "/sysUser/list";
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public Object delete(Integer id){
        log.info("[ delete()====================");
        HashMap<String,Object> resultMap = new HashMap<>();
        TSysUser user = userService.getUserInfoById(id);
        final int delete = userService.delete(id);
        if (delete>0){
            System.out.println("成功删除");
            resultMap.put("delResult","true");
        }else{
            System.out.println("删除失败");
            resultMap.put("delResult","false");
        }
        log.debug("JSON.toJSONString(resultMap)="+JSON.toJSONString(resultMap));
        return JSON.toJSONString(resultMap);
    }

    /**
     * 转到修改用户视图
     * @param model 模型
     * @param session 会话
     * @return 转到修改用户视图
     */
    @GetMapping("/toUpdate")
    public String toUpdate(Model model,HttpSession session,Integer id){
        //log.info("[ toUpdate() id="+id+";================");
        System.out.println(("[ toUpdate() ;================"));
        if( session.getAttribute( SessionConstant.USER_SESSION ) == null ){
            return "redirect:/user/toLogin";
        }
        TSysUser user2 = (TSysUser) session.getAttribute( SessionConstant.USER_SESSION );
        System.err.println("user2.id="+user2.getId());
        TSysUser user = userService.getUserInfoById(user2.getId());
        System.err.println("=toUpdate():user.id="+user.getId());
        model.addAttribute(SessionConstant.USER_SESSION ,user);
        System.out.println("转到/sysUser/update.jsp");
        return "/sysUser/update";
    }

    @PostMapping("/updateUser")
    public String updateUser(Model model,HttpSession session,
                             String account,String realName,
                             Integer sex,@DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday,
                             String phone,String address,
                             Integer roleId){
        log.info("updateUser============");
        /*User Admin = (User) session.getAttribute("user");
        User user = new User();
        user.setUserCode(account);
        user.setUserName(realName);
        user.setGender(sex);
        user.setBirthday(birthday);
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(roleId);
        user.setModifyBy(Admin.getId());
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        user.setModifyDate(date);
        Boolean flag = userService.updateUser(user);
        if (flag) {
            System.out.println("修改成功");
            return "redirect:/user/toUserList";
        }*/
        System.out.println("修改失败");
        return "/sysUser/update";
    }

    @GetMapping("/toUpdateUserPassword")
    public String toUpdateUserPassword(){
        //转到修改密码视图
        return "sysUser/updatePassword";
    }

    @PostMapping("/updateUserPassword")
    public String updateUserPassword(@RequestParam("id") Integer id, @RequestParam("newPassword") String newPassword){
        System.out.println("[ 用户id:" + id + "新密码:" + newPassword+" ]");

        Boolean flag = userService.updateUserPassword(id,newPassword);
        if (flag){
            System.out.println("成功");
            return "frame";
        }
        return "/sysUser/updatePassword";
    }

    /**
     * 验证旧密码是否正确
     * @param session
     * @return
     */
    /*@ResponseBody()
    @GetMapping("/oldPasswordIf")
    public Object oldPasswordIf(HttpSession session,@RequestParam("oldpassword") String oldpassword,@RequestParam("newpassword") String newpassword){
        System.out.println("旧密码:" + oldpassword + "新密码:" + newpassword);
        HashMap<String,Object> map = new HashMap<>();
        if (null != session.getAttribute(SessionConstant.USER_SESSION)){
            TSysUser user = (TSysUser) session.getAttribute("user");
            if (null != oldpassword){
                if (user.getPassword().equals(oldpassword)){
                    System.out.println("旧密码正确");
                    map.put("result","true");
                }else {
                    System.out.println("旧密码错误" + user.getPassword());
                    map.put("result","false");
                }
            }else {
                System.out.println("旧密码为空");
                map.put("result","error");
            }
        }else {
            System.out.println("session失效");
            map.put("result","sessionerror");
        }
        return JSON.toJSONString(map);
    }*/

    @RequestMapping("/toUpdateUserPassword")
    public String toUpdateUserPassword(HttpSession session){
        if(session.getAttribute("user") != null){
            return "/sysUser/updatePassword";
        }
        return "redirect:/user/toLogin";
    }

}
